﻿using System.Text;

namespace doufu.Common
{
    static public class StringExtension
    {
        /// <summary>
        /// 截断字符串
        /// </summary>
        /// <param name="src"></param>
        /// <param name="limitNum">中文</param>
        /// <returns></returns>
        static public string SubStr(this string src, int limitNum = 10)
        {
            if (string.IsNullOrEmpty(src)) return string.Empty;
            limitNum = 2 * limitNum;
            src = src.Trim();
            if (Encoding.Default.GetByteCount(src) > limitNum)
            {
                var ascii = new ASCIIEncoding();
                int tempLen = 0;
                byte[] s = ascii.GetBytes(src);
                for (int i = 0; i < s.Length; i++)
                {
                    tempLen += (s[i] == 0x3f) ? 2 : 1;
                    if (tempLen > limitNum)
                    {
                        src = src.Substring(0, i) + "...";
                        return src;
                    }
                }
            }
            return src;
        }

        public static bool IsNullOrEmpty(this string src)
        {
            return string.IsNullOrEmpty(src);
        }
    }
}